<!-- 版本：
    "el-select-tree": "^2.1.1-beta.12",
    "element-ui": "^2.15.14",
 -->
<template>
    <ld-dialog :appendToBody="true" ref="dialog" :title="`${type === 'print' ? '打印机' : '刻录机'}设备`" width="456"
        @close="handleClose">
        <div>
            <el-form :model="form" ref="form" label-width="110px" :rules="rules" style="width: 80%; margin: 0px auto">
                <el-form-item :label="`${type === 'print' ? '打印机' : '刻录机'}名称`" prop="name">
                    <el-input disabled v-model="form.name"
                        :placeholder="`请输入${type === 'print' ? '打印机' : '刻录机'}名称`"></el-input>
                </el-form-item>
                <el-form-item label="授权用户" prop="ownerUserId">
                    <el-select-tree @remove-tag="removeTag" :default-checked-keys="defaultCheckedKeys" ref="treeLazy" :check-strictly="true"
                        multiple show-checkbox placeholder="请选择授权用户" :props="treeProps" lazy value-key="id" node-key="id"
                        :cache-data="cacheData" :load="handleLoad" style="width: 100%" v-model="form.ownerUserId" />
                </el-form-item>
            </el-form>
            <div class="footer">
                <el-button type="primary" :loading="loading" @click="handleSave" class="footer-btn">保存上报</el-button>
            </div>
        </div>
    </ld-dialog>
</template>
<script>
//elSelectTree版本2.1.1-beta.10
import { uid } from "uid";
import LdDialog from "@/components/LdDialog/index.vue";
export default {
    name: 'BurnDialog',
    components: {
        LdDialog
    },
    props: {
        row: {
            type: Object,
            default: () => ({})
        },
        type: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            form: {
                name: "",
                ownerUserId: [],
            },
            rules: {
                name: [{ required: true, message: "名称不能为空", trigger: 'blur' }],
                ownerUserId: [{ required: true, message: "请选择授权用户" }]
            },
            loading: false,
            treeProps: {
                label: "caption",
                value: 'id',
                children: "children",
            },
            cacheData: [],
            defaultCheckedKeys: []
        }
    },
    mounted() {
        console.log(this.row, 'this.row')
        this.form = {
            ...this.form,
            name: this.row.name
        }
        if (this.row) {
            window.chromePro.getDeviceAuthUserInfo(JSON.stringify({ deviceId: this.row.id }))
        }
        this.$bus.$on('getUserTreeFinished', this.getUserTreeFinished)
        this.$bus.$on('getDeviceAuthUserInfoFinished', this.getDeviceAuthUserInfoFinished)
        this.$bus.$on('addDeviceAuthUserInfoFinished', this.addDeviceAuthUserInfoFinished)
    },
    beforeDestroy() {
        this.$bus.$off('getUserTreeFinished', this.getUserTreeFinished)
        this.$bus.$off('getDeviceAuthUserInfoFinished', this.getDeviceAuthUserInfoFinished)
        this.$bus.$off('addDeviceAuthUserInfoFinished', this.addDeviceAuthUserInfoFinished)
    },
    methods: {
        removeTag(data) {
            this.defaultCheckedKeys = this.defaultCheckedKeys.filter(item => item !== data)
            this.cacheData = this.cacheData.filter(item=>item.userId !== data)
            
        },
        handleLoad(node, resolve) {
            console.log(node, 'node')
            this.resolve = resolve;
            const params = {
                id: node.level === 0 ? "" : node.data.id,
            };
            window.chromePro.getUserTree(JSON.stringify(params));
        },
        getUserTreeFinished(res) {
            console.log(res, "树接口");
            if (res.code === 200) {
                this.resolve(
                    res.data.map((item) => {
                        return {
                            ...item,
                            isLeaf: !item.hasChild,
                            disabled: item.type === 'user' ? false : true,
                            // leaf:!item.hasChild
                        };
                    })
                );
            }
        },
        handleClose() {
            this.$emit('close')
        },
        handleSave() {
            console.log(this.form, 'this.form')
            this.$refs.form.validate(valid => {
                if (!valid) return
                // 在编辑的时候，如果没有全部展开选中的节点，会丢失部分没有展开选中的节点
                const selectNodes = this.$refs.treeLazy.getCheckedNodes()
                console.log(selectNodes, 'selectNodes')
                let data = []
                selectNodes.map(item => {
                    data.push({ userId: item.id, userName: item.caption })
                })
                //求差集
                const divide = this.form.ownerUserId.filter(x => data.findIndex(y => y.userId === x) < 0)
                divide.map(item => {
                    this.cacheData.map(v => {
                        if (item === v.id) {
                            data.push({ userId: v.id, userName: v.caption })
                        }
                    })
                })
                const params = {
                    deviceId: this.row.id,
                    data
                }
                console.log(params, 'params')
                this.loading = true
                window.chromePro.addDeviceAuthUserInfo(JSON.stringify(params))
            })
        },
        getDeviceAuthUserInfoFinished(res) {
            console.log(res, 'res')
            if (res.code === 200) {
                res.data.map(item => {
                    item.caption = item.userName,
                        item.id = item.userId
                })
                this.cacheData = res.data;
                this.$nextTick(() => {
                    this.form.ownerUserId = this.cacheData.map(item => item.userId)
                    this.defaultCheckedKeys = this.cacheData.map(item => item.userId)
                });
            }
        },
        addDeviceAuthUserInfoFinished(res) {
            if (res.code === 200) {
                this.$message.success(res.msg)
                this.$emit('close')
                this.$emit('update')
            } else {
                this.$message.error(res.msg)
            }
            this.loading = false
        }
    }
}
</script>
<style lang="scss" scoped>
.file-box {
    display: inline-block;
    width: 130px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.footer {
    display: flex;
    justify-content: center;
    margin-top: 8px;

    .el-button {
        width: 104px;
        height: 36px;
        border: none;
        background: linear-gradient(109.97deg, #0782fb 4.3%, #41b1eb 100%);
        border-radius: 2px;
        font-family: PingFangSC-Regular;
        color: #ffffff;
        font-size: 14px;
        text-align: center;
    }
}

.template {
    font-family: PingFangSC-Regular;
    color: #0782fb;
    font-size: 12px;
}

.el-button-text {
    font-family: PingFangSC-Regular;
    color: #0782fb;
    font-size: 14px;
}
</style>